package com.ruoyi.business.service.impl;

import java.util.HashMap;
import java.util.List;

import com.ruoyi.business.domain.JtProduct;
import com.ruoyi.business.service.IJtProductService;
import com.ruoyi.business.utils.SnGenerateUtil;
import com.ruoyi.business.vo.StocktakingVo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.domain.JtStocktakingItem;
import com.ruoyi.business.mapper.JtStocktakingMapper;
import com.ruoyi.business.domain.JtStocktaking;
import com.ruoyi.business.service.IJtStocktakingService;
import com.ruoyi.common.core.text.Convert;

/**
 * 库存盘点Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-06-13
 */
@Service
public class JtStocktakingServiceImpl implements IJtStocktakingService 
{
    @Autowired
    private JtStocktakingMapper jtStocktakingMapper;
    @Autowired
    private IJtProductService jtProductService;
    /**
     * 查询库存盘点
     * 
     * @param stocktakingId 库存盘点主键
     * @return 库存盘点
     */
    @Override
    public JtStocktaking selectJtStocktakingByStocktakingId(Long stocktakingId)
    {
        return jtStocktakingMapper.selectJtStocktakingByStocktakingId(stocktakingId);
    }

    /**
     * 查询库存盘点列表
     * 
     * @param jtStocktaking 库存盘点
     * @return 库存盘点
     */
    @Override
    public List<JtStocktaking> selectJtStocktakingList(JtStocktaking jtStocktaking)
    {
        return jtStocktakingMapper.selectJtStocktakingList(jtStocktaking);
    }

    /**
     * 新增库存盘点
     * 
     * @param jtStocktaking 库存盘点
     * @return 结果
     */
    @Transactional
    @Override
    public int insertJtStocktaking(JtStocktaking jtStocktaking)
    {
        jtStocktaking.setCreateTime(DateUtils.getNowDate());
        int rows = jtStocktakingMapper.insertJtStocktaking(jtStocktaking);
        insertJtStocktakingItem(jtStocktaking);
        return rows;
    }

    /**
     * 修改库存盘点
     * 
     * @param jtStocktaking 库存盘点
     * @return 结果
     */
    @Transactional
    @Override
    public int updateJtStocktaking(JtStocktaking jtStocktaking)
    {
        jtStocktaking.setUpdateTime(DateUtils.getNowDate());
        jtStocktakingMapper.deleteJtStocktakingItemByStocktakingId(jtStocktaking.getStocktakingId());
        insertJtStocktakingItem(jtStocktaking);
        return jtStocktakingMapper.updateJtStocktaking(jtStocktaking);
    }

    /**
     * 批量删除库存盘点
     * 
     * @param stocktakingIds 需要删除的库存盘点主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtStocktakingByStocktakingIds(String stocktakingIds)
    {
        jtStocktakingMapper.deleteJtStocktakingItemByStocktakingIds(Convert.toStrArray(stocktakingIds));
        return jtStocktakingMapper.deleteJtStocktakingByStocktakingIds(Convert.toStrArray(stocktakingIds));
    }

    /**
     * 删除库存盘点信息
     * 
     * @param stocktakingId 库存盘点主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteJtStocktakingByStocktakingId(Long stocktakingId)
    {
        jtStocktakingMapper.deleteJtStocktakingItemByStocktakingId(stocktakingId);
        return jtStocktakingMapper.deleteJtStocktakingByStocktakingId(stocktakingId);
    }

    /**
     * 新增库存盘点明细信息
     * 
     * @param jtStocktaking 库存盘点对象
     */
    public void insertJtStocktakingItem(JtStocktaking jtStocktaking)
    {
        List<JtStocktakingItem> jtStocktakingItemList = jtStocktaking.getJtStocktakingItemList();
        Long stocktakingId = jtStocktaking.getStocktakingId();
        if (StringUtils.isNotNull(jtStocktakingItemList))
        {
            List<JtStocktakingItem> list = new ArrayList<JtStocktakingItem>();
            for (JtStocktakingItem jtStocktakingItem : jtStocktakingItemList)
            {
                jtStocktakingItem.setStocktakingId(stocktakingId);
                jtStocktakingItem.setCreateBy(ShiroUtils.getSysUser().getUserName());
                jtStocktakingItem.setCreateTime(DateUtils.getNowDate());
                list.add(jtStocktakingItem);
            }
            if (list.size() > 0)
            {
                jtStocktakingMapper.batchJtStocktakingItem(list);
            }
        }
    }


    /**
     * 库存盘点导入
     * @param list
     * @param optName
     * @return
     */
    @Transactional
    @Override
    public String importStocktaking(List<StocktakingVo> list, String optName, Long warehouseId){
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new BaseException("未发现可导入的信息！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        JtProduct param = new JtProduct();
        List<JtStocktakingItem> stocktakingItemList = new ArrayList<>();
        Long  preTotalQty = 0L, postTotalQty = 0L;

        int i = 1;
        for (StocktakingVo entity : list) {
            i++;
            if(StringUtils.isEmpty(entity.getProductCode())){
                failureNum++;
                failureMsg.append("<br/>").append(i).append("、未填写 产品编码！");
                continue;
            }
            if (entity.getQty() == null) {
                failureNum++;
                failureMsg.append("<br/>").append(i).append("、[").append(entity.getProductCode()).append("]未填写 数量！");
                continue;
            }
            param.setProductCode(null);

            //产品数据是否存在
            param.setProductCode(entity.getProductCode());
            List<JtProduct> productList = jtProductService.selectJtProductList(param);

            if(productList.size() == 0){
                failureNum++;
                failureMsg.append("<br/>").append(i).append("、[").append(entity.getProductCode()).append("]商品信息不存在！");
                continue;
            } else {
                if(productList.size() == 1){
                    JtProduct jtProductDb = productList.get(0);

                    JtStocktakingItem stocktakingItem = new JtStocktakingItem();
                    stocktakingItem.setPostInventoryQty(entity.getQty());
                    stocktakingItem.setPreInventoryQty(jtProductDb.getStock());

                    stocktakingItem.setProfitLossQty(entity.getQty() - jtProductDb.getStock());
                    stocktakingItem.setStatus(1);
                    stocktakingItem.setProductCode(jtProductDb.getProductCode());
                    stocktakingItem.setProductId(jtProductDb.getProductId());
                    stocktakingItem.setStyleCode(jtProductDb.getStyleNo());
                    stocktakingItem.setWarehousePosition(entity.getWarehousePosition());
                    stocktakingItemList.add(stocktakingItem);
                    preTotalQty += jtProductDb.getStock();
                    postTotalQty += entity.getQty();

                    JtProduct product = new JtProduct();
                    product.setProductId(jtProductDb.getProductId());
                    product.setStock(entity.getQty());
                    int rows = jtProductService.updateJtProduct(product);
                    if(rows > 0) {
                        successNum++;
                        successMsg.append("<br/>").append(i).append("、").append(jtProductDb.getProductName()).append(" [").append(entity.getProductCode()).append("] 成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>").append(i).append("、").append(jtProductDb.getProductName()).append("[").append(entity.getProductCode()).append("] 失败");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(i).append("、[").append(entity.getProductCode()).append("] 查询到多条记录。");
                    continue;
                }
            }
        }

        if(list.size() == 0){
            failureMsg.append("无数据导入!");
            throw new BaseException(failureMsg.toString());
        }

        JtStocktaking jtStocktaking = new JtStocktaking();
        jtStocktaking.setWarehouseId(warehouseId);
        jtStocktaking.setDocumentDate(DateUtils.getNowDate());
        jtStocktaking.setPostTotalQty(postTotalQty);
        jtStocktaking.setPreTotalQty(preTotalQty);
        jtStocktaking.setInventoryListNumber(SnGenerateUtil.stocktakingOrderNumber());
        jtStocktaking.setValidationTime(DateUtils.getNowDate());
        jtStocktaking.setReviewer(ShiroUtils.getSysUser().getUserName());
        jtStocktaking.setStatus(1);
        jtStocktaking.setJtStocktakingItemList(stocktakingItemList);
        int rows = insertJtStocktaking(jtStocktaking);
        if(rows > 0) {
            successNum++;
            successMsg.append("<br/>").append("成功");
        } else {
            failureNum++;
            failureMsg.append("<br/>").append("失败");
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BaseException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
